# -*- encoding: utf-8 -*-

import random
import sys

import pygame
from pygame.locals import *

from comps.snake import SNAKE

from comps.setting import SETTING


def start():
    # 游戏初始化
    pygame.init()
    setting = SETTING
    window = pygame.display.set_mode((setting.W, setting.H))
    pygame.display.set_caption('胜奕的像素蛇 1.0')
    clock = pygame.time.Clock()
    # 初始化蛇
    snake = SNAKE((setting.W, setting.H), 10, 20, [])

    # 定义坐标/颜色/方向
    head_color = Color(100, 0, 100)
    body_color = Color(255, 200, 220)
    food_color = Color(255, 100, 0)
    bg_color = Color(220, 220, 220)
    direct = 'down'

    # 游戏循环
    quit = True
    while quit:
        bodies = snake.getBody()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit = False
            elif event.type == pygame.KEYDOWN:
                if (event.key == 273 or event.key == 119) and direct != 'down':
                    direct = 'up'
                elif (event.key == 274 or event.key == 115) and direct != 'up':
                    direct = 'down'
                elif (event.key == 276 or event.key == 97) and direct != 'right':
                    direct = 'left'
                elif (event.key == 275 or event.key == 100) and direct != 'left':
                    direct = 'right'

        # 渲染-画出来
        pygame.draw.rect(window, bg_color, (0, 0, setting.W, setting.H))
        for body in bodies:
            pygame.draw.rect(window, head_color, (body[0], body[1], 10, 10))

        # 移动头
        if direct == 'left':
            snake.moveBody(2)
        elif direct == 'right':
            snake.moveBody(3)
        elif direct == 'up':
            snake.moveBody(0)
        elif direct == 'down':
            snake.moveBody(1)

        pygame.display.flip()

        # 设置帧频
        clock.tick(20)


if __name__ == "__main__":
    start()
